package org.ehe.business.project.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.ehe.business.engineer.service.QuarterlyScoreService;
import org.ehe.business.monitor.MonitorMethod;
import org.ehe.business.project.domain.ProjectAssignmentEntity;
import org.ehe.business.project.domain.ProjectDifficultyConfigEntity;
import org.ehe.business.project.domain.ProjectEntity;
import org.ehe.business.project.domain.ProjectSolution;
import org.ehe.business.project.domain.bo.ProjectEntityBo;
import org.ehe.business.project.domain.dto.*;
import org.ehe.business.project.domain.vo.ProjectProgressVO;
import org.ehe.business.project.domain.vo.ProjectVo;
import org.ehe.business.overdue.extract.ProjectDataExtractor;
import org.ehe.business.project.service.ProjectDifficultyConfigService;
import org.ehe.business.project.service.ProjectService;
import org.ehe.common.core.domain.R;
import org.ehe.common.core.utils.StringUtils;
import org.ehe.common.log.annotation.Log;
import org.ehe.common.log.enums.BusinessType;
import org.ehe.common.mybatis.core.page.PageQuery;
import org.ehe.common.mybatis.core.page.TableDataInfo;
import org.ehe.common.satoken.utils.LoginHelper;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 项目管理
 *
 * @author :zhangnn
 * @className :ProjectController
 * @description: 项目管理功能
 * @date 2025-07-16 11:28:20
 */
@RestController
@RequestMapping("/project")
@RequiredArgsConstructor
public class ProjectController {
    private final ProjectService projectService;
    private final QuarterlyScoreService scoringService;
    private final ProjectDifficultyConfigService difficultyConfigService;

    /**
     * 项目列表
     */
    @GetMapping("/list")
    public TableDataInfo<ProjectVo> list(ProjectEntityBo project, PageQuery pageQuery) {
        return projectService.selectPageProjectList(project, pageQuery);
    }

    /**
     * 获取项目列表（树形结构）
     * 权限控制：
     * - admin用户可以看到全部项目
     * - 普通工程师只能看到分配给自己的项目（包括完整的父子树形结构）
     */
    @PostMapping("/tree")
    public R<List<ProjectEntity>> getProjectTree(@RequestBody ProjectEntityBo bo) {
        // 判断当前用户是否为超级管理员
        if (LoginHelper.isSuperAdmin()) {
            // admin可以看到全部项目
            bo.setFlag("1");
        } else {
            // 普通工程师只能看到分配给自己的项目
            bo.setFlag("3");
        }

        List<ProjectEntity> projectTree = projectService.getProjectTree(bo);
        return R.ok(projectTree);
    }

    /**
     * @param projectId 项目ID
     *                  获取项目详情
     * @return
     */
    @GetMapping("/{projectId}")
    public R<ProjectEntity> getProjectDetail(@PathVariable Long projectId) {
        ProjectEntity project = projectService.getProjectDetail(projectId);
        return R.ok(project);
    }

    /**
     * 新增项目
     *
     * @param request 请求参数
     * @return
     */
    @SaCheckPermission("project:index:add")
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目管理", linkType = "project", businessType = BusinessType.INSERT, idField = "id", nameField = "name")
    @PostMapping("/create")
    public R createProject(@RequestBody ProjectCreateRequest request) {
        try {
            return R.ok("项目新增成功", projectService.createProject(request));
        } catch (Exception e) {
            return R.fail("项目新增失败", e.getMessage());
        }
    }

    /**
     * 修改项目
     *
     * @param projectId 项目ID
     * @param request   请求参数
     * @return
     */
    @SaCheckPermission("project:index:edit")
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目更新", linkType = "project", businessType = BusinessType.UPDATE, idField = "id", nameField = "name")
    @PostMapping("/{projectId}")
    public R<Void> updateProject(@PathVariable Long projectId,
            @Valid @RequestBody ProjectCreateRequest request) {
        projectService.updateProject(projectId, request);
        return R.ok("项目更新成功！");
    }

    /**
     * 更新项目状态
     *
     * @param projectId 项目ID
     * @param request   请求参数
     * @return
     */
    @SaCheckPermission("project:index:editStatus")
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目状态更新", linkType = "project", businessType = BusinessType.UPDATE, idField = "status", nameField = "projectName")
    @PostMapping("/{projectId}/status")
    public R<Void> updateProjectStatus(@PathVariable Long projectId,
            @Valid @RequestBody ProjectCreateRequest request) {
        String status = request.getStatus();
        projectService.updateProjectStatus(projectId, status);
        return R.ok("状态更新成功！");
    }

    /**
     * 预估完成天数的修改
     */
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目时长更新", linkType = "project", businessType = BusinessType.UPDATE, idField = "estimatedHours", nameField = "projectName")
    @PostMapping("/{projectId}/{estimatedHours}")
    public R<Void> updateProjectStatus(@PathVariable Long projectId, @PathVariable int estimatedHours) {
        projectService.updateProjectEstimatedHours(projectId, estimatedHours);
        return R.ok("项目（时长）更新成功！");
    }

    /**
     * 删除项目
     *
     * @param projectId 项目ID
     * @return
     */
    @SaCheckPermission("project:index:remove")
    @Log(title = "项目删除", linkType = "project", businessType = BusinessType.DELETE, idField = "id", nameField = "name")
    @DeleteMapping("/{projectId}")
    public R<Void> deleteProject(@PathVariable Long projectId) {
        projectService.deleteProject(projectId);
        return R.ok("删除成功！");
    }

    /**
     * 搜索项目
     *
     * @param request 搜索参数
     * @return
     */
    @SaCheckPermission("project:index:query")
    @GetMapping("/search")
    public R<List<ProjectEntity>> searchProjects(@RequestBody ProjectSearchRequest request) {
        List<ProjectEntity> projects = projectService.searchProjects(request);
        return R.ok(projects);
    }

    /**
     * 分配项目
     *
     * @param request
     * @return
     */
    @Log(title = "项目分配", linkType = "project", businessType = BusinessType.ASSIGNMENT, idField = "id", nameField = "name")
    @PostMapping("/assign")
    public R<ProjectAssignmentEntity> assignProject(@RequestBody AssignProjectRequest request) {
        return R.ok("项目分配成功", projectService.assignProject(request.getProjectId(), request.getEngineerId()));
    }

    /**
     * 完成项目
     *
     * @param request
     */
    @Log(title = "项目完成", linkType = "project", businessType = BusinessType.COMPLETE, idField = "id", nameField = "name")
    @PostMapping("/complete")
    public R completeProject(@RequestBody CompleteProjectRequest request) {
        scoringService.completeProject(request);
        return R.ok("完成项目");

    }

    /**
     * 获取项目统计信息
     */
    @GetMapping("/statistics")
    public R<Map<String, Object>> getProjectStatistics() {
        Map<String, Object> statistics = projectService.getProjectStatistics();
        return R.ok(statistics);
    }

    /**
     * 批量更新项目状态
     *
     * @param request 请求参数
     * @return
     */
    @Log(title = "批量更新项目状态", linkType = "project", businessType = BusinessType.UPDATE, idField = "id", nameField = "name")
    @PostMapping("/batch-status")
    public R<Void> batchUpdateStatus(@RequestBody BatchUpdateStatusRequest request) {
        projectService.saveOrUpdateBatch1(request.getProjectIds(), request.getStatus());
        return R.ok("批量更新项目状态成功");
    }

    /**
     * 批量删除项目
     *
     * @param projectIds 参数ids
     * @return
     */
    @Log(title = "批量删除项目", linkType = "project", businessType = BusinessType.DELETE, idField = "id", nameField = "name")
    @DeleteMapping("/batch")
    public R<Void> batchDeleteProjects(@RequestBody List<Long> projectIds) {
        projectService.batchDeleteProjects(projectIds);
        return R.ok("批量删除成功");
    }

    /**
     * 获取项目进度报告
     */
    @GetMapping("/progress-report")
    public R<List<ProjectProgressVO>> getProjectProgressReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        List<ProjectProgressVO> report = projectService.getProjectProgressReport(startDate, endDate);
        return R.ok(report);
    }

    /**
     * 导出项目数据
     *
     * @param response
     * @param status     状态
     * @param difficulty 难度
     */
    @GetMapping("/export")
    public R exportProjects(HttpServletResponse response,
            @RequestParam(required = false) String status,
            @RequestParam(required = false) String difficulty) {
        projectService.exportProjects(response, status, difficulty);
        return R.ok("数据导出成功");
    }

    /**
     * 项目难度列表
     */
    @GetMapping("/difficultyList")
    public R<List<ProjectDifficultyConfigEntity>> getDifficultyList() {
        List<ProjectDifficultyConfigEntity> list = difficultyConfigService.queryList();
        return R.ok(list);
    }

    /**
     * 项目接受能力判断
     */
    @PostMapping("/checkProjectDifficultyByLevel")
    public R<String> checkProjectDifficultyByLevel(@RequestBody ProjectCreateRequest request) {
        String msg = projectService.checkProjectDifficultyByLevel(request);
        return R.ok("根据人员级别判断可以接受的项目难度", msg);
    }

    /**
     * 提交
     *
     * @param projectId 项目ID
     * @return
     */
    @SaCheckPermission("project:index:submit")
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目状态更新", linkType = "project", businessType = BusinessType.UPDATE, idField = "status", nameField = "projectName")
    @PostMapping("/submitProject/{projectId}")
    public R<ProjectEntity> submitProject(@PathVariable Long projectId) {
        ProjectEntity project = projectService.submitProject(projectId);
        return R.ok("状态更新成功！", project);
    }

    /**
     * 审核通过
     */
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目审批-通过", linkType = "project", businessType = BusinessType.COMPLETE, idField = "projectName", nameField = "projectName")
    @PostMapping("/approve/{projectId}/{auditUser}")
    public R<ProjectEntity> approveProject(@PathVariable Long projectId,
            @PathVariable String auditUser) {
        try {
            ProjectEntity project = projectService.approveProject(projectId, auditUser);
            return R.ok("审核通过成功", project);
        } catch (Exception e) {
            return R.fail("审核通过失败: " + e.getMessage());
        }
    }

    /**
     * 审核拒绝
     */
    @MonitorMethod(bizType = "projectOverdue", extractor = ProjectDataExtractor.class)
    @Log(title = "项目审批-驳回", linkType = "project", businessType = BusinessType.REJECT, idField = "projectName", nameField = "projectName")
    @PostMapping("/reject/{projectId}/{auditUser}")
    public R<ProjectEntity> rejectProject(@PathVariable Long projectId,
            @PathVariable String auditUser) {
        try {
            ProjectEntity project = projectService.rejectProject(projectId, auditUser);
            return R.ok("审核拒绝成功，已启动超期监控", project);
        } catch (Exception e) {
            return R.fail("审核拒绝失败: " + e.getMessage());
        }
    }

}
